package com.iscale.controller;

import com.iscale.event.OrderEffectEvent;
import com.iscale.model.entity.BaseRegionInfo;
import com.iscale.model.entity.SysDictionary;
import com.iscale.service.SysDictionaryService;
import com.iscale.util.ResponseCode;
import com.iscale.util.Result;
import com.iscale.util.StringUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * <p>
 * 字典 前端控制器
 * </p>
 *
 * @author Andychen
 * @since 2017-03-08
 */
@Api(value = "数据字典理模块",description = "数据字典管理模块")
@Controller
@RequestMapping("/sysDictionary")
public class SysDictionaryController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysDictionaryController.class);

    @Autowired
    SysDictionaryService dictionaryService;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private RedisTemplate<String, List<SysDictionary>> redisTemplate;

    @ApiOperation(value = "添加/更新数据字典", httpMethod = "POST", produces = "application/json", response = Result.class)
    //    @RequiresPermissions("user:insert")
    @ResponseBody
    @RequestMapping(value = "addSysDictionary", method = RequestMethod.POST)
    public Result addSysDictionary(
            @ApiParam(value = "名称", required = true) @RequestParam(defaultValue = "", required = true) String name,
            @ApiParam(value = "字典组id", required = false) @RequestParam(defaultValue = "", required = false) Long pid,
            @ApiParam(value = "键", required = false) @RequestParam(defaultValue = "", required = false) String keyName,
            @ApiParam(value = "值", required = false) @RequestParam(defaultValue = "", required = false) String keyValue,
            @ApiParam(value = "描述", required = false) @RequestParam(defaultValue = "", required = false) String description,
            @ApiParam(value = "是否可删除", required = false) @RequestParam(defaultValue = "", required = false) Integer isFinal
    ) throws Exception {
        ResponseCode responseCode = dictionaryService.saveOrUpdateDictionary(new SysDictionary( name,pid,keyName,keyValue,description,isFinal));
        //dictionaryService.insertOrUpdate(new SysDictionary( name,pid,keyName,keyValue,description,isFinal));
        //eventPublisher.publishEvent(new OrderEffectEvent("001"));
        if(null==responseCode){
            //发送消息更新缓存
            threadPoolTaskExecutor.execute(new reflushSysDictionaryCache());
        }else{
            return Result.error(responseCode);
        }
        return Result.success(responseCode);
    }

    @ApiOperation(value = "根据keyName查询", httpMethod = "POST", produces = "application/json", response = Result.class)
    //    @RequiresPermissions("user:insert")
    @ResponseBody
    @RequestMapping(value = "getSysDictionaryByKey", method = RequestMethod.POST)
    public Result getSysDictionaryByKey(
            @ApiParam(value = "键", required = true) @RequestParam(defaultValue = "", required = true) String keyName
    ) throws Exception {
        String value = dictionaryService.getSysDictionaryByKey(keyName);
        return Result.success(value);
    }

    @ApiOperation(value = "查找数据字典", httpMethod = "POST", produces = "application/json", response = Result.class)
    //    @RequiresPermissions("user:insert")
    @ResponseBody
    @RequestMapping(value = "selectDictionary", method = RequestMethod.POST)
    public Result selectDictionary(
            @ApiParam(value = "组id", required = false) @RequestParam(defaultValue = "", required = false) Long pid,
            @ApiParam(value = "键名字", required = false) @RequestParam(defaultValue = "", required = false) String keyName
    ) throws Exception {
        List<SysDictionary> ls = dictionaryService.selectDictionary(pid,keyName);
        return Result.success(ls);
    }


    @ApiOperation(value = "查找数据字典组", httpMethod = "POST", produces = "application/json", response = Result.class)
    //    @RequiresPermissions("user:insert")
    @ResponseBody
    @RequestMapping(value = "selectDictionaryGroup", method = RequestMethod.POST)
    public Result selectDictionaryGroup() throws Exception {
        List<SysDictionary> ls = dictionaryService.selectDictionaryGroup();
        return Result.success(ls);
    }


    @ApiOperation(value = "刷新数据字典缓存", httpMethod = "POST", produces = "application/json", response = Result.class)
    //@RequiresPermissions("user:insert")
    @ResponseBody
    @RequestMapping(value = "reflushSysDictionary", method = RequestMethod.POST)
    public Result reflushSysDictionary(){
        threadPoolTaskExecutor.execute(new reflushSysDictionaryCache());
        return Result.success("");
    }

    /**
     * 刷新字典缓存
     */
    protected class reflushSysDictionaryCache implements Runnable{
        @Override
        public void run() {
            List<SysDictionary> list = dictionaryService.selectList(null);
            redisTemplate.opsForValue().set("system-dictionary",list);
            log.debug("======刷新数据字典缓存=====");
        }
    }


}
